# -*- coding: utf-8 -*-
# @Author   : xiongjianwen
# @Time     : 2023/1/11 16:30
# @File     : handle_postion.py
# @Project  : BwProCost_Auto_v1


import uiautomation as auto
import time


def tree_select_item(tree, row, column):
    row -= 1
    column -= 1
    if tree is None:
        return
    if not isinstance(tree, auto.TreeControl):
        return
    pattern = tree.GetPattern(auto.PatternId.GridPattern)
    if pattern is None:
        return
    # 获取控件行列数
    rowcount = pattern.RowCount
    columncount = pattern.ColumnCount
    if row < 0 or row > rowcount:
        return
    if column < 0 or column > columncount:
        return

    # 获取指定行列单元格
    item = pattern.GetItem(row, column)
    if item is None:
        return
    # 点击单元格中心位置
    item.Click(ratioX=0.5, ratioY=0.5)


def tree_click_header(tree, column):
    column -= 1
    if tree is None:
        return
    if not isinstance(tree, auto.TreeControl):
        return
    pattern = tree.GetPattern(auto.PatternId.GridPattern)
    if pattern is None:
        return

    # 获取控件列数
    columncount = pattern.ColumnCount
    if column < 0 or column > columncount:
        return

    # 获取所有列头
    headers = []
    for item, depth in auto.WalkControl(tree):
        if isinstance(item, auto.HeaderControl):
            headers.append(item)
        else:
            break
    if column < 0 or column > len(headers):
        return
    # 获取指定列号列头
    header = headers[column]
    # 点击列头
    header.Click(ratioX=0.5, ratioY=0.5)


def walk_tree(tree):
    if tree is None:
        return
    if not isinstance(tree, auto.TreeControl):
        return
    pattern = tree.GetPattern(auto.PatternId.GridPattern)
    if pattern is None:
        return
    # 获取控件行列数
    rowcount = pattern.RowCount
    columncount = pattern.ColumnCount

    # 遍历所有单元格
    for row in range(0, rowcount):
        for column in range(0, columncount):
            # 获取指定行列单元格
            item = pattern.GetItem(row, column)
            auto.Logger.Write(item.Name + '        ')
        auto.Logger.Write('\n')


if __name__ == '__main__':
    # 查找主窗口
    app_windows = auto.WindowControl(searchDepth=1, Name='变电站工程.zwzj - 博微电力建设计价通软件')
    # 查找工程量列表控件
    # tree = app_windows.TreeControl(searchDepth=17, ClassName='ui::control::CStandTreeTableView', Name='')
    tree = app_windows.WindowControl(Name='工程量').TreeControl(ClassName='ui::control::CStandTreeTableView',searchDepth=17)

    # tree_click_header(tree, 1)
    # tree_select_item(tree,13,4)

    # 测试控件数据遍历
    walk_tree(tree)

    # 测试控件选中
    # tree_click_header(tree, 1)
    # tree_click_header(tree, 2)
    # tree_click_header(tree, 3)
    # tree_click_header(tree, 4)
    # tree_click_header(tree, 5)
    # tree_click_header(tree, 6)
    # tree_select_item(tree,1,1)
    # time.sleep(2)